<template>
  <Form ref="validForm" :model="formData" :rules="ruleValidate">
    <Row :gutter="32">
      <Col span="18">
        <Upload
            ref="upload"
            :show-upload-list="false"
            :format="['jpg','jpeg','png']"
            :max-size="20480"
            :default-file-list="defaultList"
            type="drag" :on-success="handleSuccess"
            action="http://localhost:8080/test/upload"> <!-- 设置上传头像后台地址 -->
          <div style="padding: 20px 0">
            <Icon type="ios-camera" size="52" style="color: #3399ff"></Icon>
            <p>请上传用户头像</p>
          </div>
        </Upload>
      </Col>
      <Col span="6">
        <div class="demo-upload-list" v-for="item in uploadList">
          <template v-if="item.status === 'finished'">
            <Image :src="item.url" fit="cover" width="100%" height="100%"/>
          </template>
          <template v-else>
            <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
          </template>
        </div>
      </Col>
    </Row>

    <Row :gutter="32">
      <Col span="12">
        <FormItem label="用户名" label-position="top" prop="username">
          <Input v-model="formData.username" placeholder="请输入用户名"/>
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="初始默认密码" label-position="top">
          <Input v-model="formData.password" placeholder="请输入密码"/>
        </FormItem>
      </Col>
    </Row>

    <Row :gutter="32">
      <Col span="12">
        <FormItem label="真实姓名" label-position="top" prop="realName">
          <Input v-model="formData.realName" placeholder="请输入真实姓名"/>
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="手机号" label-position="top" prop="tel">
          <Input v-model="formData.tel" placeholder="请输入手机号"/>
        </FormItem>
      </Col>
    </Row>

    <Row :gutter="32">
      <Col span="12">
        <FormItem label="所属组织机构" label-position="top" prop="orgs">
          <TreeSelect v-model="formData.orgs" multiple show-checkbox :data="orgs" />
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="电子邮箱" label-position="top" prop="email">
          <Input v-model="formData.email" placeholder="请输入电子邮箱"/>
        </FormItem>
      </Col>

    </Row>


    <Row :gutter="32">
      <Col span="12">
        <FormItem label="职务" label-position="top">
          <Select v-model="formData.positions" multiple>
            <Option v-for="item in positions" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
      </Col>

      <Col span="12">
        <FormItem label="性别" label-position="top">
          <Select v-model="formData.sex">
            <Option v-for="item in sexList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
      </Col>
    </Row>


    <Row :gutter="32">
      <Col span="12">
        <FormItem label="出生日期" label-position="top">
          <DatePicker type="date" v-model="formData.birth" style="width: 100%;"
                      placeholder="请选择出生日期" :options="options"/>
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="用户状态" label-position="top" prop="state" class="user-state">
          <Select v-model="formData.state">
            <Option v-for="item in state" :value="item.value" :key="item.label">{{ item.label }}</Option>
          </Select>
        </FormItem>
      </Col>
    </Row>


  </Form>

  <div class="demo-drawer-footer">
    <Button style="margin-right: 8px" @click="$emit('close-win', false)">关闭</Button>
    <Button type="primary" @click="handleForm">保存</Button>
  </div>
</template>

<script>
export default {
  props: {
    userId: {type: Number, required: false},
  },
  data() {
    return {
      formData: {
        username: "",
        password: "123456",
        realName: "",
        tel: "",
        orgs: [],
        sex: "",
        birth: "",
        email: "",
        state: 1
      },
      defaultList: [{url: new URL("../assets/default-user.png", import.meta.url).href}], // 默认头像，修改的时候使用
      uploadList: [],
      orgs: [
        {
          title: '奇酷网络科技有限公司',
          expand: true,
          value: '1',
          selected: false,
          checked: false,
          children: [
            {
              title: '教学部',
              expand: true,
              value: '2',
              selected: false,
              checked: false,
            }
          ]
        },
        {
          title: '结善缘有限公司',
          expand: true,
          value: '3',
          selected: false,
          checked: false,
        },
        {
          title: '点兔娱乐有限公司',
          expand: true,
          value: '4',
          selected: false,
          checked: false,
        }
      ],
      positions: [
        {
          value: '1',
          label: '董事长'
        },
        {
          value: '2',
          label: '总经理'
        },
        {
          value: '3',
          label: '员工'
        }
      ],
      state: [{value: 1, label: "启用"}, {value: 0, label: "禁用"}] ,
      sexList: [
        {value: "m", label: "男"}, {value: "f", label: "女"},
      ],
      options: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        }
      },
      ruleValidate: {
        username: [
          {required: true, message: "用户名不允许为空", trigger: 'blur'},
          {type: "string", max: 100, message: "用户名过长", trigger: 'blur'},
          {type: "string", pattern: /^\w+$/, message: "用户名只允许字母、数字和下划线组成", trigger: 'blur'},
        ],
        realName: [
          {required: true, message: "真实姓名不允许为空", trigger: 'blur'},
          {type: "string", max: 30, message: "真实姓名过长", trigger: 'blur'},
        ],
        tel: [
          {required: true, message: "手机号不允许为空", trigger: 'blur'},
          {type: "string", pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: 'blur'},
        ],
        orgs: [
          {required: true, type: "array", min: 1, message: "至少选择一个组织机构", trigger: 'change'},
        ],
        email: [
          {required: true, message: "邮箱不允许为空", trigger: 'blur'},
          {
            type: "string",
            pattern: /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/,
            message: "邮箱格式不正确",
            trigger: 'blur'
          },
        ],
        state: [
          {type: "enum", enum: [0, 1] , message: "状态必须是一个boolean类型的值", trigger: "blur"}
        ],
      }
    }
  },
  created(){
      // 如果是更新、查询对应的用户信息, 无论是否有用户ID,查询组织机构和职务
      this.queryData();
  },
  emits: ["close-win"],
  methods: {
    queryData() {
      // 模拟异步
      setTimeout(() => {
        this.formData = {
          username: "admin",
          realName: "超级管理员",
          tel: "13312344321",
          orgs: [],
          sex: "m",
          birth: "1990-11-11",
          email: "admin@git.com",
          state: 1
        };
        this.defaultList = [{url: "https://file.iviewui.com/images/image-demo-2.jpg"}];
        this.uploadList = {...this.defaultList};
      }, 50);
    },
    handleSuccess(response, file, fileList) {
      console.log(response) // 上传接口返回的JSON数据
      // 从响应中 获取 上传图片的地址
      file.url = 'https://file.iviewui.com/images/image-demo-3.jpg';
      this.uploadList = [file];
    },
    handleForm() {
      this.$refs.validForm.validate(valid => {
        if (valid) {
          if (this.userId == null) {
            this.handleSave();
          } else {
            this.handleUpdate();
          }
        }
      })
    },
    handleSave() {
      console.log("保存用户..");
      this.$emit("close-win", "save");
    },
    handleUpdate() {
      console.log("修改用户..");
      this.$emit("close-win", "update");
    },
    resetValidForm() {
      this.$refs.validForm.resetFields();
    },
  },
  mounted() {
    this.uploadList = this.$refs.upload.fileList;
  },
}
</script>

<style scoped>
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}

.demo-upload-list {
  display: inline-block;
  width: 113px;
  height: 113px;
  text-align: center;
  line-height: 113px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, .6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>